import Components from "unplugin-vue-components/vite";
import { VantResolver } from "unplugin-vue-components/resolvers";
import type { ViteConfig } from "nuxt/schema";
import {
  BASE_URL_PREFIX,
  IMAGE_FORMATS,
  VCONSOLE_SCRIPT,
  GENERATE_DIR,
} from "./config";
import packageJson from "./package.json";
import { visualizer } from "rollup-plugin-visualizer";
import postcss from "./postcss.config";
import { useEnvConfigInfo } from "./utils/index";

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  // devtools: { enabled: true },
  ssr: true,

  nitro: {
    output: {
      dir: ".output",
      serverDir: ".output/server",
      publicDir: `.output/public${GENERATE_DIR}`, // yarn generate 的时候要加上/fx
    },
    // 客户端转发
    devProxy: {
      "/api": {
        // target: "https://bdc.btcdana.org/api", // 生产
        // target: "https://pre-bdc.btcdana.org/api", // 预发
        // target: "https://test-bdc.btcdana.org/api", // 测试环境
        target: useEnvConfigInfo().devProxy,
        changeOrigin: true,
      },
    },
    // 解决: ENOENT: no such file or directory, open '.../node_modules/geoip-lite/data/geoip-country.dat'
    externals: {
      traceInclude: [
        "node_modules/geoip-lite/data/city.checksum",
        "node_modules/geoip-lite/data/country.checksum",
        "node_modules/geoip-lite/data/geoip-city.dat",
        "node_modules/geoip-lite/data/geoip-city6.dat",
        "node_modules/geoip-lite/data/geoip-city-names.dat",
        "node_modules/geoip-lite/data/geoip-country.dat",
        "node_modules/geoip-lite/data/geoip-country6.dat",
      ],
    },
    esbuild: {
      options: {
        target: ["es2015", "chrome87", "safari12"],
      },
    },
  },

  // 该配置用于服务端请求转发
  routeRules: {
    "/api/**": {
      // proxy: `https://test-bdc.btcdana.org/api/**`, // 测试
      // proxy: `https://pre-bdc.btcdana.org/api/**`, // 预发
      proxy: useEnvConfigInfo().routeRules,
    },
  },

  components: [
    {
      path: "~/components/public", // 默认为 '~/components'
    },
  ],

  serverHandlers: [
    { route: "/errorkey", handler: "~/server/api/errorkey.ts" },
    { route: "/removelog", handler: "~/server/api/removelog.ts" },
    { route: "/servelog", handler: "~/server/api/logreport.ts" },
    { route: "/getservelog", handler: "~/server/api/getlog.ts" },
    { route: "/trackReport", handler: "~/server/api/track-report.ts" },
    { route: "/trackinfo", handler: "~/server/api/track-info.ts" },
    { route: "/analyticsEvent", handler: "~/server/api/track-analytics-event.ts" },
    
  ],

  webpack: {
    extractCSS: true,
    optimizeCSS: true,
    optimization: {
      splitChunks: {
        cacheGroups: {
          styles: {
            name: "styles",
            test: /\.(css|vue|scss)$/,
            chunks: "all",
            enforce: true,
          },
        },
      },
    },
    warningIgnoreFilters: [],
  },

  dir: {
    layouts: "layouts",
  },

  vite: {
    ssr: {
      noExternal: ["vant"],
    },
    optimizeDeps: {
      exclude: [
        // 'public-ip',
      ],
    },
    plugins: [
      Components({
        resolvers: [VantResolver()],
      }),
      visualizer(),
    ],
    test: {
      deps: {
        inline: ["vant"],
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/styles/default.scss";',
        },
      },
    },
    build: {
      modern: true, // Nuxt 3 支持现代模式，可以生成现代 JavaScript 代码以提高性能和兼容性;
      include: ["@babel/runtime/regenerator"],
      rollupOptions: {
        external: ["sharp"],
      },
      target: ["es2015", "chrome87", "safari12"],

      // rollupOptions: {
      //   output: {
      //     manualChunks: (id) => {
      //       if (id.includes("node_modules")) {
      //         return "vendor";
      //       }
      //     },
      //   },
      // },
      // sourcemap: false,
      // minify: false, // 禁止代码压缩
    },
  } as ViteConfig,

  build: {
    transpile: ["nuxt/app", "vant", "core-js"], // "@qiun/vue-ucharts"
  },

  experimental: {
    externalVue: true,
    writeEarlyHints: false,
    inlineSSRStyles: false,
  },

  runtimeConfig: {
    baseURL: BASE_URL_PREFIX,
    public: {
      WEB_NODE_ENV: process.env.WEB_NODE_ENV,
      version: `${packageJson.version} <===> ${packageJson.versionTime}`,
    },
  },

  app: {
    baseURL: BASE_URL_PREFIX,
    head: {
      meta: [
        {
          content: `width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover`,
          name: "viewport",
        },
      ],
      script: [
        {
          children: `
          // window.addEventListener('error', function(event) {
          //   console.log('捕获到错误:', event.message);
          //   console.log('错误来源:', event.filename);
          //   console.log('行号:', event.lineno);
          //   console.log('列号:', event.colno);
          //   let msg = event.message+'=='+event.filename+'=='+event.lineno+'=='+event.colno
          //   // let msg = JSON.stringify(event) 
          //   alert(msg)
          //   // 阻止错误冒泡和默认的错误处理
          //   event.preventDefault();
          // });
          // window.onerror = function(message, source, lineno, colno, error) {
          //   console.log('捕获到错误:', message);
          //   alert('捕获到错误:'+message) // 捕获到错误:Uncaught SyntaxError:Unexpected token
          //   // 防止默认处理（例如浏览器的错误提示）
          //   return true;
          // };
          `,
          type: "text/javascript",
        },
        // {
        //   src: "https://unpkg.com/callapp-lib@3.1.2/dist/index.umd.js",
        // },
        // {
        //   // dayjs的转时区功能的polyfill  由于加载耗时、且暂时用处不大，先移除
        //   src: "https://unpkg.com/date-time-format-timezone@latest/build/browserified/date-time-format-timezone-complete-min.js",
        // },
        // generate 是打包 index.html 时候的环境变量
        ...(process.env.WEB_NODE_ENV !== "prod" &&
        process.env.WEB_NODE_ENV !== "generate" &&
        process.env.WEB_NODE_ENV !== "dev" &&
        process.env.NODE_ENV != "development"
          ? VCONSOLE_SCRIPT
          : []),
        // ...(process.env.WEB_NODE_ENV == "test" ? VCONSOLE_PLUGIN : []),
      ],
      // link: [
      //   {
      //     rel: "stylesheet",
      //     href: BASE_URL_PREFIX + "/fonts/font.scss",
      //   },
      // ],
    },
    // pageTransition: { name: "page", mode: "out-in" },
    // layoutTransition: { name: "page", mode: "out-in" },
    // keepalive: true,
  },

  modules: [
    // "@nuxt/devtools",
    "@vant/nuxt",
    // "@aceforth/nuxt-optimized-images",
    "@nuxtjs/i18n",
    "@nuxt/image",
    [
      "@pinia/nuxt",
      {
        autoImports: [
          // 自动引入 `usePinia()`
          "defineStore",
          // 自动引入 `usePinia()` 并重命名为 `usePiniaStore()`
          ["defineStore", "definePiniaStore"],
        ],
      },
    ],
    // "@nuxtjs/device",
    "nuxt-vite-legacy",
  ],

  legacy: {
    targets: [
      "defaults",
      "not IE 11",
      "maintained node versions",
      "last 2 versions",
      "> 1%",
      "iOS >= 8",
      "Firefox ESR",
      "Android >= 4.1",
    ],
    renderLegacyChunks: false,
    modernPolyfills: ["es.global-this", "es/object", "es/array"],
  },

  image: {
    format: IMAGE_FORMATS,
    domains: [
      "btcdana.org",
      "forexdana.trade",
      "bdc.btcdana.org",
      "asset.onetrader.online",
    ],
    densities: [1, 2, 3],
    presets: {
      // 默认
      default: {
        modifiers: {
          fit: "cover",
          // format: IMAGE_FORMATS.join(","),
          quality: 100,
        },
      },
    },
    screens: {
      xs: 320,
      sm: 640,
      md: 768,
      lg: 1024,
      xl: 1280,
      xxl: 1536,
      "2xl": 1536,
    },
    staticFilename: "[publicPath]/img/[name].[hash:7].[ext]",
  },

  i18n: {
    vueI18n: "./i18n.config.ts",
    locales: [
      // "en_US",
      "en",
      "in_en",
      "ph",
      // "in",
      "indonesia",
      "VI",
      // "zh",
      "zh_hk",
      "mys",
      "pt",
    ],
    defaultLocale: "en", // 这个不能删除
    strategy: "prefix_except_default", // 定义策略
    // skipSettingLocaleOnNavigate: true, // 这个配合03.callApp.client中的defaultLocale才能更改默认值 -- 如果true，则在导航到新区域设置时不会设置区域设置。如果您想在使用 自行设置区域设置之前等待页面转换结束，这非常有用。请参阅等待页面转换中的更多信息。finalizePendingLocaleChange
    // detectBrowserLanguage: {
    //   useCookie: true,
    //   cookieKey: "i18n_redirected",
    //   redirectOn: "root", // recommended
    // },
  },

  css: ["@/styles/var.scss", "@/styles/mixin.scss", "@/styles/global.scss"],

  //  require("./postcss.config")
  postcss: postcss,

  compatibilityDate: "2024-09-16",
});
